using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using WeifenLuo.WinFormsUI.Docking;
using WeifenLuo.WinFormsUI.Security;

namespace WeifenLuo.WinFormsUI.Base
{
    public partial class MainBaseForm : Form
    {
		public DeserializeDockContent m_deserializeDockContent;
        public AppSecurity mUserRight;
        public Ctrl_Database mCtrlDB;
        public Ctrl_Security mCtrlScur;
        public DialogResult mDlgResult = DialogResult.None;
        public bool mbClicked = true;

        public string ms_UserID = string.Empty;
		
        public MainBaseForm()
        {
            InitializeComponent();
            mUserRight = new AppSecurity();
            toolBar.ImageList = imgList;
            foreach(ToolStripButton tbb in toolBar.Items)
                tbb.Image = imgList.Images[tbb.Tag.ToString()];
            ToolStripSeparator tbs = new ToolStripSeparator();
            toolBar.Items.Insert(12, tbs);
            tbs = new ToolStripSeparator();
            toolBar.Items.Insert(10, tbs);
            tbs = new ToolStripSeparator();
            toolBar.Items.Insert(9, tbs);
            tbs = new ToolStripSeparator();
            toolBar.Items.Insert(6, tbs);
            tbs = new ToolStripSeparator();
            toolBar.Items.Insert(2, tbs);
        }

        protected virtual void MainBaseForm_Load(object sender, System.EventArgs e)
        {
            try
            {
                stbUserLogin.Text = "Login ...";
                mCtrlDB = new Ctrl_Database();
                // Get Connection string from config XML file then Set to the connection string variable and show it to the status bar
                mCtrlDB.SetConnectionString();
                stbDBName.Text = "Database name" + ": " + mCtrlDB.GetDBName();
                SetParamSys2Registry(); // need to review

                FormLogin lfrmLogin = new FormLogin();
                lfrmLogin.Owner = this;
                if (lfrmLogin.ShowDialog() == DialogResult.OK)
                {
                    FinishingLogin(lfrmLogin.UserName);
                    mDlgResult = DialogResult.OK;
                }
                else
                    RefreshToolbar();
                //// Docking Panel ////////////////////////////////////////////////////////////////////////////////////////
                //string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
                //if (File.Exists(configFile))
                //    dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////

            }
            catch (Exception ex)
            {
                string[] lsa_param = new string[2];
                lsa_param[0] = ex.Message;
                lsa_param[1] = "MainFormLoad";
                MessageBox.Show("Error " + lsa_param[0] + "at function: " + lsa_param[1], ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Ctrl_LOG.Print("MainBaseForm", "MainBaseForm_Load Event", "Error message: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }

        protected virtual void EnableMainmenuFunction(bool ab_switch)
        { }

        private void LogOut()
        {
            try
            {
                this.ResumeLayout(true);
                Cursor = Cursors.WaitCursor;
                // Close all the MdiChild form.
                while (this.ActiveMdiChild != null)
                    this.ActiveMdiChild.Close();
                dockPanel.Hide();
                

                mnu_LogIn.Enabled = true;
                mnu_LogOut.Enabled = false;
                ms_UserID = "";
                stbUserLogin.Text = "Log out";
                stbDBName.Text = "Database name:";
                EnableMainmenuFunction(false);
                RefreshToolbar();
                mDlgResult = DialogResult.None;
                Cursor = Cursors.Default;
                this.ResumeLayout(false);
            }
            catch (Exception ex)
            {
                string[] lsa_param = new string[2];
                lsa_param[0] = ex.Message;
                lsa_param[1] = "mnu_LogOut_Click";
                MessageBox.Show("Error " + lsa_param[0] + "at function: " + lsa_param[1], ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("MainBaseForm", "Log Out", "Error message: " + ex.Message);
                Application.Exit();
            }
        }

        private void LogIn()
        {
            stbUserLogin.Text = "Log in ...";
            FormLogin lfrmLogin = new FormLogin();
            lfrmLogin.Owner = this;
            if (lfrmLogin.ShowDialog() == DialogResult.OK)
            {
                stbDBName.Text = "Database name" + ": " + mCtrlDB.GetDBName();
                FinishingLogin(lfrmLogin.UserName);
                mDlgResult = DialogResult.OK;
            }
            else
            {
                RefreshToolbar();
                if (ms_UserID == "")
                {
                    stbUserLogin.Text = "Log out";
                    stbDBName.Text = "Database name: ";
                }
            }
            Cursor = Cursors.Default;
        }

        #region Finishing Login
        private void FinishingLogin(string as_UserName)
        {   // Do some things when connecting to DB successfully.
            ms_UserID = as_UserName;
            stbUserLogin.Text = "User ID: " + ms_UserID;
            stbWorkDate.Text = DateTime.Now.ToShortDateString();
            mCtrlScur = new Ctrl_Security();
            mUserRight.GetRightSet(mCtrlScur.GetUserAccessRight(ms_UserID));

            if (!mUserRight.GetRightSet(mCtrlScur.GetUserAccessRight(ms_UserID)))
            {
                MessageBox.Show("Get user right failed. Please make sure the config file is correct!", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                SetLogout(false);
                ms_UserID = "";
                return;
            }

            SetLogin(false);
            SetLogout(true);

            // Docking Panel ////////////////////////////////////////////////////////////////////////////////////////
            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
            if (File.Exists(configFile) && dockPanel.Contents.Count <= 0)
                dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
            else
                dockPanel.Show();

            
            
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            EnableMainmenuFunction(true);
            RefreshToolbar();
            Cursor = Cursors.Default;
        }
        #endregion
        
        #region Set Param Sys2Registry
        private void SetParamSys2Registry()
        {
            /*bool lbConfiguration = false;
            //Registry is an abstract class, so we do nothing on it.
            RegistryKey HkCu = Registry.CurrentUser.OpenSubKey("Control Panel");
            RegistryKey HkMine = HkCu.OpenSubKey("International");
            // get sShortDate from registry
            string ls_sShortDate = HkMine.GetValue("sShortDate", "").ToString();
            // save sShortDate to registry
            if (!ls_sShortDate.Equals("dd/MM/yyyy"))
            {
                SavesShortDateToRegistry("dd/MM/yyyy");
                lbConfiguration = true;
            }
            HkMine.Flush();
            HkCu.Flush();
            HkMine.Close();
            if (lbConfiguration)
            {
                MessageBox.Show("System had just configured some things. Please restart sytem again after system shut down!", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
            }*/
        }
        #endregion
        #region Saves ShortDate To Registry
        private void SavesShortDateToRegistry(string as_sShortDate)
        {	// First, we have to navigate to the HKEY_CURRENT_USER/Control Panel/International registry key
            /*RegistryKey HkCu = Registry.CurrentUser.OpenSubKey("Control Panel", true);
            RegistryKey HkMine = HkCu.OpenSubKey("International", true);

            HkMine.SetValue("sShortDate", as_sShortDate);
            HkMine.SetValue("sDate", "/");
            HkMine.Close();*/
        }
        #endregion

        #region Refresh Toolbar
        public void RefreshToolbar()
        {
            if (ms_UserID == "" || ms_UserID == null)
            {
                SetSecurity(false);
                SetMainFunction(false);
                SetLogin(true);
                SetLogout(false);
            }
            else
            {
                SetSecurity(true);
                SetMainFunction(true);
                if (mUserRight.IsInAdminGroup(ms_UserID))
                    SetRight4Admin(true);
                else
                    SetRight4Admin(false);
                SetLogin(false);
                SetLogout(true);
            }
            SetEditText(false);
            SetDataManipulation(false);
            SetRefreshData(false);
        }
        #endregion

        private void SetLogin(bool ab_switch)
        {
            mnu_LogIn.Enabled = ab_switch;// Login
        }

        private void SetLogout(bool ab_switch)
        {
            mnu_LogOut.Enabled = ab_switch; // Logout
        }

        private void SetSecurity(bool ab_switch)
        {
            mnu_ChangePass.Enabled = ab_switch; // Change Password
            mnu_User.Enabled = ab_switch; // User Info
            mnu_GroupUser.Enabled = ab_switch; // Group Info
            mnu_AccRight.Enabled = ab_switch; // Access Right
        }

        protected virtual void SetMainFunction(bool ab_switch)
        {
            //Add code for enable/disable menu functions
        }

        private void SetRight4Admin(bool ab_switch)
        {
            mnu_User.Enabled = ab_switch;// User Info	
            mnu_GroupUser.Enabled = ab_switch;// Group Info
            mnu_AccRight.Enabled = ab_switch;// Access Right
        }

        private void SetEditText(bool ab_switch)
        {
            // not available
            /*MainCommandHolder.Commands[4].Enabled = ab_switch;// Cut
            MainCommandHolder.Commands[5].Enabled = ab_switch;// Copy
            MainCommandHolder.Commands[6].Enabled = ab_switch;// Paste
            MainCommandHolder.Commands[7].Enabled = ab_switch;// Copy Previous
            MainCommandHolder.Commands[8].Enabled = ab_switch;// Select All
            */
        }

        private void SetDataManipulation(bool ab_switch)
        {
            SetNavigator(ab_switch);
            mnu_Print.Enabled =       // Print Direct menu
            mnu_PrintPre.Enabled =    // Print Preview menu
            mnu_Find.Enabled =        // Find menu
            mnu_List.Enabled =        // List menu
            tbb_List.Enabled =        // List toolbar
            tbb_PrintDir.Enabled =    // Print Direct toolbar
            tbb_PrintPre.Enabled = ab_switch;// Print Preview toolbar

            SetDataActions(ab_switch);
            SetValidate(ab_switch);
            SetRefreshData(ab_switch);
        }

        private void SetDataActions(bool ab_switch)
        {
            SetNavigator(ab_switch);
            mnu_AddNew.Enabled =        // Add New menu
            mnu_Delete.Enabled =        // Delete menu
            mnu_Modify.Enabled =        // Modify menu
            tbb_Modify.Enabled =        // Modify toolbar
            tbb_Add.Enabled =           // Add New toolbar
            tbb_Delete.Enabled = ab_switch;// Delete toolbar
        }

        private void SetNavigator(bool ab_switch)
        {
            mnu_FirstRecord.Enabled =           // Move First menu
            mnu_PreviousRecord.Enabled =        // Move Previous menu
            mnu_NextRecord.Enabled =            // Move Next menu
            mnu_LastRecord.Enabled =            // Move Last menu
            tbb_FirstRec.Enabled =              // Move First toolbar
            tbb_LastRec.Enabled =               // Move Last toolbar
            tbb_NextRec.Enabled =               // Move Next toolbar
            tbb_PreviousRec.Enabled = ab_switch;// Move Previous toolbar
        }

        private void SetValidate(bool ab_switch)
        {
            mnu_Save.Enabled =      // Save menu
            mnu_Cancel.Enabled =    // Cancel menu
            tbb_Save.Enabled =      // Save toolbar
            tbb_Cancel.Enabled = ab_switch; // Cancel toolbar
        }

        private void SetRefreshData(bool ab_switch)
        {
            mnu_Refresh.Enabled = ab_switch;// Refresh data
        }

        protected virtual DialogResult ShowFormMainFunctions()
        {
            // This window will be opened only one time in the MDI
            Cursor = Cursors.WaitCursor;
            if (ms_UserID == "")
            {
                MessageBox.Show("Log in irregular. Access denied", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Cursor = Cursors.Default;
                return DialogResult.Cancel;
            }
            else return DialogResult.OK;

            // Display menu functions form
        }

        public bool CheckAccessRight(string asTitle, string asFormName)
        {
            if (mUserRight.GetAccess(asFormName).mb_read) return true;
            Cursor = Cursors.Default;
            MessageBox.Show("'" + asTitle + "' access denied. Please contact to HRM Administrator!", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }

        #region Print method
        private void print()
        {
            if (this.ActiveMdiChild != null)
            {
                Cursor = Cursors.WaitCursor;
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.print();
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Print preview method
        private void printPreview()
        {
            FormBaseData frmData = null;
            if (this.ActiveMdiChild != null)
            {
                Cursor = Cursors.WaitCursor;
                frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.print_preview();
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Modify method
        private void modify()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.modify();
            }
        }
        #endregion

        #region Add New method
        private void addnew()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.add();
            }
        }
        #endregion

        #region Delete method
        private void delete()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.delete();
            }
        }
        #endregion

        #region Save method
        private void save()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.save();
            }
        }
        #endregion

        #region Cancel method
        private void cancel()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.cancel();
            }
        }
        #endregion

        #region First Record method
        private void first()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.move_first();
            }
        }
        #endregion

        #region Previous Record method
        private void previous()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.move_previous();
            }
        }
        #endregion

        #region Next method
        private void next()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.move_next();
            }
        }
        #endregion

        #region Last 
        private void last()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.move_last();
            }
        }
        #endregion

        #region Refresh
        private void refresh()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.RefreshData();
            }
        }
        #endregion

        #region List
        private void list()
        {
            if (this.ActiveMdiChild != null)
            {
                FormBaseData frmData = (FormBaseData)this.ActiveMdiChild;
                frmData.list();
            }
        }
        #endregion

        protected virtual void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mbClicked = true;
            switch (((ToolStripMenuItem)sender).Name)
            {
                case "mnu_LogIn":
                    LogIn();
                    break;

                case "mnu_LogOut":
                    LogOut();
                    break;

                case "mnu_ChangePass":
                    // add code here
                    break;

                case "mnu_ChangeDB":
                    //add code here
                    break;

                case "mnu_Close":
                    // add code here
                    break;

                case "mnu_CloseAll":
                    break;

                case "mnu_CloseAllButThisOne":
                    break;

                case "mnu_Exit":
                    Close();
                    break;

                case "mnu_ExitWithoutSavingLayout":
                    // add code here
                    break;

                case "mnu_Print":
                    break;

                case "mnu_PrintPre":
                    printPreview();
                    break;

                case "mnu_Modify":
                    modify();
                    break;

                case "mnu_AddNew":
                    addnew();
                    break;

                case "mnu_Delete":
                    delete();
                    break;

                case "mnu_Save":
                    save();
                    break;

                case "mnu_Cancel":
                    cancel();
                    break;

                case "mnu_Find":
                    
                    break;

                case "mnu_Functions":
                    break;

                case "mnu_List":
                    list();
                    break;

                case "mnu_Refresh":
                    refresh();
                    break;

                case "mnu_FirstRecord":
                    first();
                    break;

                case "mnu_PreviousRecord":
                    previous();
                    break;

                case "mnu_NextRecord":
                    next();
                    break;

                case "mnu_LastRecord":
                    last();
                    break;

                case "mnu_ToolBar":
                    
                    break;

                case "mnu_StatusBar":
                    break;

                case "mnu_Output":
                    break;

                case "mnu_TaskList":
                    break;

                default :
                    mbClicked = false;
                    break;
            }

        }

        public DialogResult ShowForm(FormBaseData frmBaseData)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                frmBaseData.MdiParent = this;
                frmBaseData.Show();
            }
            else
                frmBaseData.Show(dockPanel);
            return DialogResult.OK;
        }

        private void ToolStripButton_Click(object sender, EventArgs e)
        {
            switch (((ToolStripButton)sender).Name)
            {
                case "tbb_PrintDir":
                    print();
                    break;
                case "tbb_PrintPre":
                    printPreview();
                    break;
                case "tbb_FirstRec":
                    first();
                    break;
                case "tbb_PreviousRec":
                    previous();
                    break;
                case "tbb_NextRec":
                    next();
                    break;
                case "tbb_LastRec":
                    last();
                    break;
                case "tbb_Modify":
                    modify();
                    break;
                case "tbb_Add":
                    addnew();
                    break;
                case "tbb_Delete":
                    delete();
                    break;
                case "tbb_List":
                    list();
                    break;
                case "tbb_Save":
                    save();
                    break;
                case "tbb_Cancel":
                    cancel();
                    break;
                case "tbb_Help":
                    //Help();
                    break;
            }
        }

    }
}